/*

Input: newdata/estimation_prep_ltw18_stadtbez.dta [prepared district-level panel]

Output: Figure D.15

Task: Robustness: Effect on party outcomes by mail, district level 

*/	
	
* PULL: District-level panel
	use "$newdata/estimation_prep_ltw18_stadtbez.dta", clear
		
********************************************************************************
	//	 Prep Estimation //
********************************************************************************
	
	// gen total turnout
	gen sbez_turnout_tot_req = sbez_turnout_urne_ohne + sbez_turnout_pos_req
	
	drop *heitsforschung *rrp
	
// insert missings instead of zeros for party shares where party wasn't on the ballot
	foreach v of varlist sbez_shr_* {
		forvalues j =1/8 {
			qui su `v' if wahl_id==`j'
			qui replace `v' =. if r(mean)==0 & wahl_id==`j'
		}
		assert `v' <1 if !missing(`v')
		qui replace `v'= `v'*100 // rescale 0-100
	}	
	
	// gen votes rel to eligible voter
	* in KOW14 und KOW20 => #votes > #eligible voters!
	foreach v of varlist sbez_anz_* {
		gen 	 rel_`v'  =  100* `v' /wahlber_gesamt if !inlist(wahl_id,3,8)
		replace  rel_`v' =  100* `v' /(wahlber_gesamt*80) if inlist(wahl_id,3,8)
		assert inrange(rel_`v',0,100) | missing(rel_`v')
	}		

	// GEN party shares by MAIL
	* in KOW14 und KOW20 => #votes > #eligible voters!
	foreach v of varlist sbez_anz_p* {
		gen 	 shr_`v'  =  100* `v' /(waehler_21) if !inlist(wahl_id,3,8)
		replace  shr_`v' =  100* `v' /((waehler_21)*80) if inlist(wahl_id,3,8)
	}		
	
	// classify 6 largest parties in Left-Right (ONLY POSTAL)
	gen shr_sbez_anz_pleft 	= shr_sbez_anz_pdielinke + shr_sbez_anz_pspd + shr_sbez_anz_pgruene
	gen shr_sbez_anz_pcons 	= shr_sbez_anz_pfdp + shr_sbez_anz_pcsu  + shr_sbez_anz_pfreiewaehler 
	gen rel_sbez_anz_pleft 	= rel_sbez_anz_pdielinke + rel_sbez_anz_pspd + rel_sbez_anz_pgruene
	gen rel_sbez_anz_pcons 	= rel_sbez_anz_pfdp + rel_sbez_anz_pcsu  + rel_sbez_anz_pfreiewaehler 
	
	** Define Event= first time precinct is >70% reassigned
	* Gen treat50_simple = Binary indicator for treat_simple 
	gen treat50_simple = (treat_simple >=.7) 
	
	* Gen  fulltotreat50= Total nbr. of times a precinct is treated (>70% reassigned)
	bys stadtbez: egen fulltottreat50 = total(treat50_simple)	
	
	
* Gen relevant indicators	
	// gen Ei50 = unit-specific date of treatment (never-treated = missing)
	cap drop Ei50
	gen tmp_wahl_id = (-1)*wahl_id
	bys stadtbez (treat50_simple tmp_wahl_id): gen Ei50 = wahl_id[_N] if fulltottreat50>0 // wahl_id where first FULL-treatment (treat_simple==1)
	lab var Ei50 "date of treatment,treat=70% reassigned, NT=."
	
	// gen K := "relative time", i.e. the number periods since treated (never-treated = missing)
	cap drop K50
	gen K50 = wahl_id- Ei50	
	lab var K50 "rel. time, treat=70% reassigned, NT=."
	
	// gen D treatment indicator (=1 post treatmeant, never-treated = 0)
	cap drop D50
	gen D50 = K50>=0 & Ei50!=. 
	lab var D50 "post-treatment dummy, treat=70% reassigned, NT=0"
	
	// smpl_trim50: drop observations after SECOND treatment (>50%) kicks in
	cap drop 	smpl_trim50
	gen 		smpl_trim50 = 1
	gen tmp_other_treats = (treat50_simple > 0 & K50 != 0)		// identify second treatments after t0
	bys stadtbez (wahl_id): replace smpl_trim50 = 0 if (tmp_other_treats == 1 | smpl_trim50[_n-1] ==0) // set missing after second treatment kicks in		
	
	tab stadtbez if K50==0
	count  if K50==0			// how many out of 25 treated
	
********************************************************************************
	// Event Study: Party Outcomes, DISTRICT level, Figure D15 //
********************************************************************************

	// gen leads and lags
	cap drop L* F*
	forvalues l = 7(-1)1 {
		gen F`l'event = K50==-`l'
	}	
	forvalues l = 0/7 {
		gen L`l'event = K50==`l'
	}
	order F1event, last

	// Estimate baseline ES
	estimates clear
	global dpv rel_sbez_anz_pleft shr_sbez_anz_pleft rel_sbez_anz_pcons  shr_sbez_anz_pcons
	
	
	foreach v of varlist $dpv {	
		qui reghdfe `v' F7event-L7event F1event $ctr $wgt if smpl_trim50 ==1, absorb(i.wahl_id i.stadtbez) cluster(stadtbez)
		estimates store `v'
		
		qui su `v' $wgt
		local mean_`v':di %12.1f r(mean)
		local m`v'=subinstr("`mean_`v''"," ","",.)
	}
		
		
	// PLOT: LEFT RIGHT PARTY TURNOUT
	event_plot  rel_sbez_anz_pleft  rel_sbez_anz_pcons , ///
	stub_lag(L#event ) stub_lead(F#event ) plottype(scatter) ciplottype(rcap) ///
	together perturb(-0.1(0.2)0.1) trimlead(4) trimlag(2) noautolegend ///
	graph_opt(xtitle("") ytitle("Party turnout in %""(estimates)", size(medsmall)) xlabel(-4(1)2) xtitle("Election since reassignment") ///
		legend(pos(12) order(1 "Left-wing (`mrel_sbez_anz_pleft' %)" 3 "Right-wing (`mrel_sbez_anz_pcons' %)") row(1) region(style(none)) size(medsmall) title("Outcomes (means):",size(medsmall) bexpand just(left))) ///
		xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid)) ylabel(, angle(horizontal)) ///
		name(turnout, replace)) ///
	lag_opt1(msymbol(O) msize(2.5pt) color(maroon)) 	lag_ci_opt1(color(maroon)) ///
	lag_opt2(msymbol(S) msize(2.5pt) color(black)) lag_ci_opt2(color(black))	
	
	// PLOT: LEFT RIGHT PARTY VOTE SHARES
	event_plot  shr_sbez_anz_pleft shr_sbez_anz_pcons , ///
	stub_lag(L#event ) stub_lead(F#event ) plottype(scatter) ciplottype(rcap) ///
	together perturb(-0.1(0.2)0.1) trimlead(4) trimlag(2) noautolegend ///
	graph_opt(xtitle("") ytitle("Party vote share in %""(estimates)", size(medsmall)) xlabel(-4(1)2) xtitle("Election since reassignment") ///
		legend(pos(12) order(1 "Left-wing (`mshr_sbez_anz_pleft' %)" 3  "Right-wing (`mshr_sbez_anz_pcons' %)"   ) row(1) region(style(none)) size(medsmall) title("Outcomes (means):",size(medsmall) bexpand just(left))) ///
		xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid)) ylabel(, angle(horizontal)) ///
		name(shares, replace) ) ///
	lag_opt1(msymbol(O) msize(2.5pt) color(maroon))  lag_ci_opt1(color(maroon)) ///
	lag_opt2(msymbol(S) msize(2.5pt) color(black)) lag_ci_opt2(color(black))	

	
* Test for equality (note: since different outcomes => need to duplicate data)
frame change default
frame copy default tmp, replace
frame tmp{	
	// duplicate dataset
	gen id=_n
	expand 2
	
	// gen dataset id
	bys id: gen idset = _n-1
	
	// rename outcomes
	gen 	y_shr = shr_sbez_anz_pleft 	 if idset==1
	replace	y_shr = shr_sbez_anz_pcons 	 if idset==0
	gen 	y_rel = rel_sbez_anz_pleft if idset==1
	replace	y_rel = rel_sbez_anz_pcons if idset==0	
	
// gen leads and lags
	cap drop L* F*
	forvalues l = 7(-1)1 {
		gen 	F`l'event = K50==-`l'
		gen 	F`l'event_int =F`l'event*idset	// interact w/ dataset id
	}	
	forvalues l = 0/7 {
		gen 	L`l'event = K50==`l'
		gen 	L`l'event_int =L`l'event*idset
	}
	order *_int, last
	order F1event*, last

	// Estimate baseline ES
	estimates clear

	global dpv y_rel y_shr 
	
	foreach v of varlist $dpv {	
		  reghdfe `v' F7event-L7event F7event_int-L7event_int F1event F1event_int c.($ctr)##c.idset $wgt if smpl_trim50 ==1, ///
			absorb(i.wahl_id##i.idset i.stadtbez##i.idset) cluster(stadtbez)
		
		estimates store `v'
					
		// PLOT differences
		event_plot  `v', ///
		stub_lag(L#event_int ) stub_lead(F#event_int ) plottype(connect) ciplottype(rcap) ///
		together  trimlead(4) trimlag(2)  noautolegend ///
		graph_opt(ytitle("Difference between estimates", size(medsmall)) xlabel(-4(1)2) xtitle("Election since reassignment", size(medsmall)) ///
			legend(pos(12) order(1 "Difference between estimates" ) row(1) region(style(none)) size(medsmall) title(" ")) ///
			xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid)) ylabel(, angle(horizontal)) ///
			name(`v',replace) ) ///
		lag_opt1(msymbol(T) msize(2.5pt) color(black) lcol(gray)) 	lag_ci_opt1(color(black))		
	}
}	
	
	* PLOT: FIGURE D15. Effects of Reassignments on Party Outcomes by Mail, district level
	graph combine turnout y_rel, row(1) 		imargins(small) xcommon ycommon name(gr1, replace) ///
		title("{bf:Panel A.} Effect on Party Turnout", nobox span bexpand justification(left) size(medsmall) )
	graph combine shares y_shr, row(1) imargins(small) xcommon ycommon name(gr2, replace) ///
		title("{bf:Panel B.} Effect on Party Vote Shares", nobox span bexpand justification(left) size(medsmall) )
	
	graph combine gr1 gr2, xcommon col(1) imargins(small) iscale(.9)	
	gr_edit .style.editstyle declared_ysize(4.2) editcopy	
	graph export "$figures/Figure_D15_ES_party_outc_two_district_postal.pdf", replace
